package com.example.glesstudy;

import static android.opengl.GLES20.*; // 静态引入

import android.graphics.SurfaceTexture;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.util.Log;

import androidx.camera.core.Preview;
import androidx.camera.view.PreviewView;
import androidx.lifecycle.LifecycleOwner;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

// 自定义渲染器   Renderer 渲染器的三个接口
public class MyGlRenderer implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener {

    private final  static  String TAG = "MyGlRenderer";
    MyGlsurfaceView myGlsurfaceView;
    private SurfaceTexture surfaceTexture;
    float[] mtx= new float[16];// 源码要求必须时16 不然异常
    ScreenFilter screenFilter;
    CameraXHelper cameraXHelper;
    private int[] mTextureId;

    public MyGlRenderer(MyGlsurfaceView myGlsurfaceView) {
    this.myGlsurfaceView = myGlsurfaceView;
    }

    /**
     * surface 创建时候 回调
     * @param gl  GL10  1。0 和 2。0 无法兼容了 就遗留下来了
     * @param config  配置项 目前用不到
     */
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {

        Log.e(TAG,"onSurfaceCreated");


        // 获取纹理id

         mTextureId = new int[1];

        //GLES20 静态引入
//        GLES20.glGenTextures();
        glGenTextures(mTextureId.length,mTextureId,0);//
         surfaceTexture = new SurfaceTexture(1);
         surfaceTexture.setOnFrameAvailableListener(this);
         cameraXHelper = new CameraXHelper((LifecycleOwner) myGlsurfaceView.getContext(), 1080, 1920, surfaceTexture);

         screenFilter = new ScreenFilter(myGlsurfaceView.getContext());


    }

    /**
     * surface 改变时候 调用此函数
     * @param gl GL10  1。0 和 2。0 无法兼容了 就遗留下来了
     * @param width
     * @param height
     */
    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        Log.e(TAG,"onSurfaceChanged");
        screenFilter.onReady(width,height);
    }

    /**
     *  绘制 每一帧 图像时 回调此函数
     * @param gl
     */
    @Override
    public void onDrawFrame(GL10 gl) {
        Log.e(TAG,"onDrawFrame");
        glClearColor(255,0,0,0);// 屏幕清理成 红色  颜色自己规定
        // GL_COLOR_BUFFER_BIT 颜色缓冲区
        // GL_DEPTH_BUFFER_BIT 深度缓冲区
        // GL_STENCIL_BUFFER_BIT 模型缓冲区
        glClear(GL_COLOR_BUFFER_BIT); // 清楚颜色

        // 绘制摄像头数据
        surfaceTexture.updateTexImage();//

        //画布 矩阵数据
        surfaceTexture.getTransformMatrix(mtx);

        screenFilter.onDrawFrame(mTextureId[0],mtx);

    }

    // 有可用的数据时 回调此函数 OnFrameAvailableListener
    @Override
    public void onFrameAvailable(SurfaceTexture surfaceTexture) {
        Log.e(TAG,"onFrameAvailable");
        // 目前是 手动模式  所以需要刷新一下RENDERMODE_WHEN_DIRTY 配合使用
        //RENDERMODE_WHEN_DIRTY
        myGlsurfaceView.requestRender();
    }
}
